package com.woniu.elderly.wares.service.impl;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.dto.WaresDTO;
import com.woniu.common.entity.Result;
import com.woniu.common.entity.WaresSku;
import com.woniu.common.entity.WaresSpu;
import com.woniu.common.entity.WaresSpuAttributeValue;
import com.woniu.elderly.wares.mapper.WaresSkuAttributeValueMapper;
import com.woniu.elderly.wares.mapper.WaresSpuAttributeValueMapper;
import com.woniu.elderly.wares.mapper.WaresSpuMapper;
import com.woniu.elderly.wares.service.WaresSkuService;
import com.woniu.elderly.wares.mapper.WaresSkuMapper;
import com.woniu.elderly.wares.utils.AddTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HyperLogLogOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
* @author Administrator
* @description 针对表【wares_sku】的数据库操作Service实现
* @createDate 2024-08-02 11:57:49
*/
@Service
@Slf4j
public class WaresSkuServiceImpl extends ServiceImpl<WaresSkuMapper, WaresSku>
    implements WaresSkuService{

    @Autowired
    private WaresSkuMapper waresSkuMapper;
    @Autowired
    private WaresSpuMapper waresSpuMapper;
    @Autowired
    private WaresSkuAttributeValueMapper waresSkuAttributeValueMapper;
    @Autowired
    private WaresSpuAttributeValueMapper waresSpuAttributeValueMapper;
    @Override
    public List<WaresDTO> getWaresSku(Integer pageIndex, Integer pageSize) {
        //查询商品信息
        List<WaresDTO> waresDTOS = waresSkuMapper.getWaresSkuDTO(pageIndex, pageSize);
        return waresDTOS;
    }

    @Override
    public List<WaresDTO> getWaresSkuAll() {
        List<WaresDTO> waresSkuDTO = waresSkuMapper.getWaresSkuDTO();
        return waresSkuDTO;
    }

    @Override
    public Result<List<WaresDTO>> getRecommend() {
        ///或者从销量高的里边挑出来几个。
        //这里采取数据随机
//        return  waresSkuMapper.getWaresSkuDTORandom();
        List<WaresDTO> waresSkuDTO = waresSkuMapper.getWaresSkuDTO(0, 10);
        ArrayList<WaresDTO> waresDTOS = new ArrayList<>();
        int num = (int)( Math.random()*waresSkuDTO.size());
        int num1 = (int)( Math.random()*waresSkuDTO.size());
        while (num == num1){
            num = (int)( Math.random()*waresSkuDTO.size());
        }
        waresDTOS.add(waresSkuDTO.get(num));
        waresDTOS.add(waresSkuDTO.get(num1));
        return Result.ok(waresDTOS);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addWaresSku(WaresDTO waresSku) {
        log.info("添加商品信息");

        System.out.println("waresSku = " + waresSku);
        System.out.println("waresSku.getSkuAttributeValueList() = " + waresSku.getSkuAttributeValueList());
        System.out.println("waresSku.getSpuAttributeValueList() = " + waresSku.getSpuAttributeValueList());
        //数据校验
        //1.判断商品名称是否为空
        if (waresSku.getSpuName() == null || waresSku.getSpuName().equals("")){
            throw new RuntimeException("商品名称不能为空");
        }
        //2.判断商品价格是否为空
        if (waresSku.getPrice() == null || waresSku.getPrice().doubleValue() < 0){
            throw new RuntimeException("商品价格不能为空");
        }
        //3.判断商品库存是否为空
        if (waresSku.getStock() == null || waresSku.getStock().intValue() < 0){
            throw new RuntimeException("商品库存不能为空");
        }
        //判断分类id是否为空
        if (waresSku.getCategoryCid() == null || waresSku.getCategoryCid().intValue() < 0){
            throw new RuntimeException("分类不能为空");
        }
       /* //判断商品id是否为空
        if (waresSku.getSpuId() == null || waresSku.getSpuId().intValue() < 0){
            throw new RuntimeException("商品id不能为空");
        }*/
        //判断商品列表是否为0,1,2
        if (waresSku.getStatus() != 0 && waresSku.getStatus() != 1 && waresSku.getStatus() != 2){
            throw new RuntimeException("商品状态只能为0,1,2");
        }
        //4.判断商品属性值列表是否为空
        if (waresSku.getSkuAttributeValueList() == null || waresSku.getSkuAttributeValueList().size() < 0){
            throw new RuntimeException("添加属性");
        }
        //判断供应商是否为空
        if (waresSku.getVender() == null || waresSku.getVender().equals("")){
            throw new RuntimeException("供应商不能为空");
        }
        //判断商品描述是否为空
        if (waresSku.getDescription() == null || waresSku.getDescription().equals("")){
            throw new RuntimeException("商品描述不能为空");
        }
        //判断商品标题是否为空
        if (waresSku.getTitle() == null || waresSku.getTitle().equals("")){
            throw new RuntimeException("商品标题不能为空");
        }
        //开始添加信息！
        log.info("开始添加商品信息");
        //判断是否是新增的商品，如果是新增的商品，则添加到wares_spu表
        WaresSpu waresSpu = waresSpuMapper.selectById(waresSku.getSpuId());
        if (waresSpu == null){
            //新增商品，添加到wares_spu表
            WaresSpu spu =new WaresSpu();
            //绑定类别
            spu.setCategoryId(waresSku.getCategoryCid());
            //新增的名字
            spu.setSname(waresSku.getSpuName());
            spu.setStatus(waresSku.getStatus());
            spu.setTitle(waresSpu.getTitle());
            spu.setDescription(waresSpu.getDescription());
            spu.setCreateTime(AddTime.getCurrentTime());
            waresSpuMapper.insert(spu);
            //添加属性
            List<WaresSpuAttributeValue> waresSpuAttributeValues = waresSku.getSpuAttributeValueList();
            waresSpuAttributeValueMapper.insert(waresSpuAttributeValues);

        }else {
            
        }

    }

    @Override
    public Page<WaresDTO> getWaresSkuPage(Integer pageIndex, Integer pageSize) {
        //判空
        if (pageIndex == null || pageSize == null){
            throw new RuntimeException("参数不能为空");
        }
        //判断pageIndex是否为负数
        if (pageIndex < 0){
            throw new RuntimeException("pageIndex不能为负数");
        }
        //判断pageSize是否为负数
        if (pageSize < 0){
            throw new RuntimeException("pageSize不能为负数");
        }

        // 创建一个分页参数对象
        Page<WaresDTO> pageParam = new Page<>();
        // 设置当前页码
        pageParam.setCurrent(pageIndex);
        // 设置每页显示数量
        pageParam.setSize(pageSize);
        pageParam.setTotal(waresSkuMapper.getWaresSkuDTO().size());
        // 调用waresSkuMapper的getWaresSkuDTOButPage方法，传入分页参数对象，获取分页数据
       pageParam.setRecords(waresSkuMapper.getWaresSkuDTO(pageIndex, pageSize));
        // 返回分页数据
        log.info("pageParam = " + pageParam.getTotal());
        return pageParam;
    }
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public void recordUV(HttpServletRequest request) {
        String userid = request.getHeader("userid");
        //解析token得到用户
//        Object user = "用户名"+token;
        //利用user和hyperloglog做uv
        HyperLogLogOperations hyperLogLogOperations = redisTemplate.opsForHyperLogLog();
        //示例uv-2024-01-25,独立日期的uv
        String key = "uv-"+AddTime.getDate();
        hyperLogLogOperations.add(key,userid);
        // 直接调用redisTemplate的execute()方法也可以，但为了清晰起见，这里假设我们想要通过ValueOperations来展示（尽管不是必需的）
        // 实际上，直接调用redisTemplate.getExpire(key, TimeUnit.SECONDS)会更直接
        // 直接使用redisTemplate的getExpire方法获取过期时间（如果存在）
        //可以不用设置过期时间，因为这个太小了12kb
       /* if (redisTemplate.getExpire(key) == -1) {
            //设置过期时间
            Boolean uv = redisTemplate.expire(key, 10, TimeUnit.SECONDS);
            log.info("key设置过期时间 = " + uv);
        }*/
//        redisTemplate.getExpire("uv", TimeUnit.SECONDS);

        }

    @Override
    public WaresDTO getWaresSkuBySkuSid(Integer skuId) {
        return  waresSkuMapper.getWaresSkuDTOBySkuId(skuId);
    }



    /**
     * 下架商品
     *
     * @param skuId 商品库存ID
     * @param status 商品状态
     * @return 无返回值
     */
    @Override
    @Transactional
    public void updateWaresSku(Integer skuId, Integer status) {
        // 创建一个新的WaresSku对象
        WaresSku waresSku = waresSkuMapper.selectById(skuId);
        if(status == 1){
            if(waresSku.getStatus() == 1){
                throw new RuntimeException("商品已经上架");
            }
            //对值进行修改
            UpdateWrapper<WaresSku> waresSkuUpdateWrapper = new UpdateWrapper<>();
            waresSkuUpdateWrapper.eq("sid", skuId).set("status", 1);
            waresSkuMapper.update(null, waresSkuUpdateWrapper);
        } else if (status == 0) {
            if(waresSku.getStatus() == 0){
                throw new RuntimeException("商品已经下架");
            }
            //对值进行修改
            UpdateWrapper<WaresSku> waresSkuUpdateWrapper = new UpdateWrapper<>();
            waresSkuUpdateWrapper.eq("sid", skuId).set("status", 0);
            waresSkuMapper.update(null, waresSkuUpdateWrapper);

        } else if (status == 2) {
            if(waresSku.getStatus() == 2){
                throw new RuntimeException("商品已经删除");
            }
            //对值进行修改
            UpdateWrapper<WaresSku> waresSkuUpdateWrapper = new UpdateWrapper<>();
            waresSkuUpdateWrapper.eq("sid", skuId).set("status", 2);
            waresSkuMapper.update(null, waresSkuUpdateWrapper);
        }else{
            throw new RuntimeException("参数错误");
        }
    }

    /**
     * 商品库存减扣
     * @param skuId
     * @param num
     */
    @Override
    public void stock(Integer skuId, Integer num) {
        WaresSku waresSku = waresSkuMapper.selectById(skuId);
        if(waresSku.getStock() < num){
            throw new RuntimeException("库存不足");
        } else if (waresSku.getStock() == num){
            log.info("减扣完库存为0");
        }else if(waresSku.getStatus() != 1){
            throw new RuntimeException("商品未上架");
        }
        UpdateWrapper<WaresSku> wrappers = new UpdateWrapper<>();
        Integer  stock = waresSku.getStock() - num;
        wrappers.eq("sid", skuId).set("stock",stock);
        waresSkuMapper.update(null, wrappers);

    }

}

  /*  public IPage<WaresDTO> getWaresSkuDTOButPage(Integer pageSize, Integer pageIndex) {
        // 创建一个分页参数对象
        IPage<WaresDTO> pageParam = new PageParam<>();
        // 设置当前页码
        pageParam.setCurrent(pageIndex);
        // 设置每页显示数量
        pageParam.setSize(pageSize);
        // 调用waresSkuMapper的getWaresSkuDTOButPage方法，传入分页参数对象，获取分页数据
        IPage<WaresDTO> waresSkuDTO = waresSkuMapper.getWaresSkuDTOButPage(pageParam);
        // 返回分页数据
        return waresSkuDTO;
    }*/

//    }




